﻿using DataService.Office.Word;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Validation;
using DocumentFormat.OpenXml.Wordprocessing;
using System;
using System.Collections.Generic;
using System.IO.Packaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace XmlCall
{
    /// <summary>
    /// 校验docx文件
    /// </summary>
    public static class WordValidateDocument
    {
        public static bool ValidateWordDocument(string filepath)
        {
            try
            {
                using (var wd = WordprocessingDocument.Open(filepath, true))
                {

                }

               // OpenXmlValidator validator = new OpenXmlValidator();
               // int count = 0;
               // IEnumerable<ValidationErrorInfo> validationErrorInfos = validator.Validate(DocumentFormat.OpenXml.Packaging.WordprocessingDocument.Open(filepath, true));
               
                //foreach (ValidationErrorInfo error in validationErrorInfos)
                //{
                //    count++;
                //    Console.WriteLine("Error " + count);
                //    Console.WriteLine("Description: " + error.Description);
                //    Console.WriteLine("ErrorType: " + error.ErrorType);
                //    Console.WriteLine("Node: " + error.Node);
                //    Console.WriteLine("Path: " + error.Path.XPath);
                //    Console.WriteLine("Part: " + error.Part.Uri);
                //    Console.WriteLine("-------------------------------------------");
                //}
                return true;
            }
            catch (Exception ex)
            {
                //Console.WriteLine(ex.Message);
            }
            return false;
        }



        public static void ValidateCorruptedWordDocument(string filepath)
        {
            // Insert some text into the body, this would cause Schema Error
            using (WordprocessingDocument wordprocessingDocument =
            WordprocessingDocument.Open(filepath, true))
            {
                // Insert some text into the body, this would cause Schema Error
                Body body = wordprocessingDocument.MainDocumentPart.Document.Body;
                Run run = new Run(new Text("some text"));
                body.Append(run);
                try
                {
                    OpenXmlValidator validator = new OpenXmlValidator();
                    int count = 0;
                    foreach (ValidationErrorInfo error in
                        validator.Validate(wordprocessingDocument))
                    {
                        count++;
                        Console.WriteLine("Error " + count);
                        Console.WriteLine("Description: " + error.Description);
                        Console.WriteLine("ErrorType: " + error.ErrorType);
                        Console.WriteLine("Node: " + error.Node);
                        Console.WriteLine("Path: " + error.Path.XPath);
                        Console.WriteLine("Part: " + error.Part.Uri);
                        Console.WriteLine("-------------------------------------------");
                    }

                    Console.WriteLine("count={0}", count);
                }

                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }

        /// <summary>
        /// 检查document.xml.rels对应关系对应的文件是否存在
        /// </summary>
        /// <param name="wordprocessingDocument"></param>
        /// <param name="relsXML">document.xml.rels的XML完整结构</param>
        /// <returns></returns>
        public static List<string> ValidateWordDocument(Package wordPackage, XmlDocument relsXML)
        {
            List<String> list = new List<string>();
            XmlNode xmlNode = relsXML.ChildNodes[1];
            XmlNodeList xmlNodeList = xmlNode.ChildNodes;
            string relativeRoot = "/word/";
            foreach (XmlNode itemXmlNode in xmlNodeList)
            {
                string targetVal = itemXmlNode.Attributes["Target"].Value;
                string targetType = itemXmlNode.Attributes["Type"].Value;
                #region 预处理
                if (targetType == XmlPackageConst.hyperlinkNamespace)
                {
                    continue;
                }
                string[] tempArray = targetVal.Split('/');
                string tempUriString = string.Empty;
                if (tempArray[0] == "..")
                {
                    tempUriString = targetVal;
                    tempUriString = tempUriString.Replace("..", "");
                }
                else
                {
                    targetVal = targetVal.Replace("/word/", "");
                    targetVal = targetVal.Replace("word/", "");
                    tempUriString = relativeRoot + targetVal;
                }
                Uri tempUri = new Uri(tempUriString, UriKind.Relative);//如果使用相对路径需要自定义Relation关系
                #endregion
                Console.WriteLine(tempUri);
                if (!wordPackage.PartExists(tempUri))
                {
                    list.Add(itemXmlNode.OuterXml);
                }
            }
            return list;
        }
    }
}
